import { onBeforeRouteLeave } from 'vue-router'
import { ref, Ref } from 'vue'

/**
 * onBeforeRouteLeave 不管是前进还是后退都会走这个回调
 * 所以要在前进时关闭dialog
 * 尽量不要在dialog里做前进的操作
 * 如果必须做前进操作，就使用 forwardInDialog 方法
 *
 * 示例：
 * const [show,forwardInDialog] = backCloseDialog(true);
    const goAbout = ()=>{
      forwardInDialog(()=>{
        router.push('/about')
      })
    }
 *
 * @param show
 */

type NupHook = () => void

type BackCloseDialogValue = [Ref<boolean>, (hook?: NupHook) => void]

export function backCloseDialog(show = false): BackCloseDialogValue {
  const showDialog = ref(show)
  const forwardFlag = ref(false)
  onBeforeRouteLeave(() => {
    // 弹窗开启
    if (showDialog.value) {
      //弹窗中向前
      if (forwardFlag.value) {
        forwardFlag.value = false
        return true
      }
      showDialog.value = false
      return false
    }
    return true
  })

  const forwardInDialog = function (callback?: NupHook) {
    forwardFlag.value = true
    callback && callback()
  }

  return [showDialog, forwardInDialog]
}
